﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SynoManager.GUI
{
    public partial class PreferencesForm : Form
    {
        private readonly MainForm form;

        public PreferencesForm()
        {
            InitializeComponent();
        }

        public PreferencesForm(MainForm form)
            :this()
        {
            this.form = form;
        }

        private void PreferencesForm_Load(object sender, EventArgs e)
        {
            var generalPreferences = new MainPreferencesPanel();

            Add("General", null, generalPreferences);
            foreach(var plugin in form.plugins.Plugins)
                plugin.PopulatePreferencesForm(treeView);

            ShowControl(generalPreferences);
        }

        private void Add(string text, Image image, PreferencesPanel control)
        {
            treeView.Nodes.Add(text, image, control);
        }

        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            PreferencesPanel control = e.Node.Tag as PreferencesPanel;

            if (control != null)
            {
                ShowControl(control);
            }
        }

        private void ShowControl(Control control)
        {
            splitContainer1.Panel2.Controls.Clear();
            splitContainer1.Panel2.Controls.Add(control);
            control.Dock = DockStyle.Fill;
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            SaveCollection(treeView.Nodes);

            Properties.Settings.Default.Save();
            DialogResult = DialogResult.OK;
        }

        private void SaveCollection(TreeNodeCollection treeNodeCollection)
        {
            foreach(TreeNode node in treeNodeCollection)
            {
                SaveCollection(node.Nodes);

                var panel = node.Tag as PreferencesPanel;
                if (panel != null)
                    panel.Save();
            }
        }
    }
}
